import { Injectable } from '@nestjs/common';
import { User } from 'src/entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { OrgsId } from 'src/globals/orgsConst';

@Injectable()
export class OrgService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  async getAll(userOrgUUID: string | null) {
    const queryB = this.userRepository
      .createQueryBuilder('user')
      .select(['user.orgNameRu as "orgRu"', 'user.orgNameEn as "orgEn"'])
      .where('user.orgNameRu IS NOT NULL')
      .andWhere('user.orgNameRu != :emptyVal', { emptyVal: '' });

    if (userOrgUUID && userOrgUUID.length > 0) {
      if (userOrgUUID === OrgsId.NFOrgUid) {
        queryB.andWhere('user.orgUuid IN (:...orgIds)', {
          orgIds: [OrgsId.AvantOrgUid, OrgsId.QvantOrgUid, OrgsId.SMMOrgUid],
        });
      }
      if (
        userOrgUUID === OrgsId.SMOrgUid ||
        userOrgUUID === OrgsId.TGOrgUid ||
        userOrgUUID === OrgsId.RoiOrgUid ||
        userOrgUUID === OrgsId.NMOrguid
      ) {
        queryB.andWhere('user.orgUuid != :orgId', {
          orgId: OrgsId.NFOrgUid,
        });
      }
    }
    return await queryB
      .orderBy('user.orgNameRu', 'ASC')
      .distinct(true)
      .getRawMany();
  }
}
